import { useState, useEffect, useRef } from "react";
import { useParams } from "react-router-dom";
import { io } from "socket.io-client";
import request from "../../../utils/request";
import "./index.css";

// 建立Socket连接
const socket = io("http://127.0.0.1:8000");

type Message = {
  id: string;
  content: string;
  type: number;
  direction: number; // 0: 接收, 1: 发送
  timestamp: number;
  userId: number;
};

type FormParam = {
  inquiryId: number;
  content: string;
  type: number;
  doctorId: number;
};

const Index = () => {
  const { id } = useParams<{ id: string }>();
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputContent, setInputContent] = useState("");
  const [isConnected, setIsConnected] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 从路由参数获取医生ID
  const doctorId = id ? parseInt(id) : 0;
  // 模拟数据 - 实际使用时应该从props或context获取
  const recordId = 1;
  const userId = 10;

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // Socket连接状态
  useEffect(() => {
    socket.on("connect", () => {
      setIsConnected(true);
      console.log("Socket connected");
    });

    socket.on("disconnect", () => {
      setIsConnected(false);
      console.log("Socket disconnected");
    });

    // 接收消息
    socket.on("message", (data: Message) => {
      setMessages(prev => [...prev, data]);
    });

    return () => {
      socket.off("connect");
      socket.off("disconnect");
      socket.off("message");
    };
  }, []);

  // 发送消息
  const handleSend = async () => {
    if (!inputContent.trim()) return;

    const messageData: FormParam = {
      inquiryId: recordId,
      content: inputContent,
      type: 1, // 文本消息
      doctorId: doctorId,
    };

    try {
      // 使用封装的axios调用API接口
      const response = await request.post("/health/user/inquiry/verify/v1/pushMessage", 
        new URLSearchParams({
          inquiryId: messageData.inquiryId.toString(),
          content: messageData.content,
          type: messageData.type.toString(),
          doctorId: messageData.doctorId.toString()
        }), {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "userId": userId.toString(),
            "sessionId": (() => {
              const userInfo = localStorage.getItem('userInfo');
              if (!userInfo) {
                throw new Error('用户未登录，请先登录');
              }
              
              try {
                const parsed = JSON.parse(userInfo);
                const sessionId = parsed.sessionId;
                
                if (!sessionId) {
                  throw new Error('用户信息不完整，请重新登录');
                }
                
                return sessionId;
              } catch (error) {
                console.error('解析用户信息失败:', error);
                throw new Error('用户信息解析失败，请重新登录');
              }
            })()
          }
        }
      );

      const result = response.data;
      
      if (result.status === "0000") {
        // 添加消息到本地
        const newMessage: Message = {
          id: Date.now().toString(),
          content: inputContent,
          type: 1,
          direction: 1, // 发送
          timestamp: Date.now(),
          userId: userId,
        };
        
        setMessages(prev => [...prev, newMessage]);
        
        // 发送Socket事件
        socket.emit("update", { ...messageData, userId });
        
        // 清空输入框
        setInputContent("");
      } else {
        console.error("发送失败:", result.message);
        alert("发送失败: " + result.message);
      }
    } catch (error) {
      console.error("发送消息失败:", error);
      alert("网络错误，请重试");
    }
  };

  // 处理回车键
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  return (
    <div className="chat-container">
      {/* 聊天头部 */}
      <div className="chat-header">
        <div className="doctor-chat-info">
          <div className="avatar">👨‍⚕️</div>
          <div className="info">
            <div className="name">医生 {doctorId}</div>
            <div className="status">
              {isConnected ? "🟢 在线" : "🔴 离线"}
            </div>
          </div>
        </div>
      </div>

      {/* 消息列表 */}
      <div className="messages-container">
        {messages.length === 0 ? (
          <div className="empty-state">
            <div className="empty-icon">💬</div>
            <div className="empty-text">开始聊天吧</div>
          </div>
        ) : (
          messages.map((message) => (
            <div
              key={message.id}
              className={`message ${message.direction === 1 ? "sent" : "received"}`}
            >
              <div className="message-content">
                {message.content}
              </div>
              <div className="message-time">
                {new Date(message.timestamp).toLocaleTimeString()}
              </div>
            </div>
          ))
        )}
        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div className="input-container">
        <div className="input-wrapper">
          <textarea
            value={inputContent}
            onChange={(e) => setInputContent(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="输入消息..."
            className="message-input"
            rows={1}
          />
          <button
            onClick={handleSend}
            disabled={!inputContent.trim()}
            className="send-button"
          >
            发送
          </button>
        </div>
      </div>
    </div>
  );
};
 
export default Index;
